package net.bcxuexi.server.stream;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import net.bcxuexi.config.Config;
import net.bcxuexi.server.SocketManager;
import net.bcxuexi.server.model.ServerSocketModel;
import net.bcxuexi.server.model.SocketModel;
import net.bcxuexi.tools.IdGen;
import net.bcxuexi.tools.MyLog;

/**
 * ServerSocket接收客户端连接
 */
public class AcceptSocket extends Thread{
	private ServerSocketModel serverSocketModel;
	public AcceptSocket(ServerSocketModel serverSocketModel){
		this.serverSocketModel = serverSocketModel;
	}
	@Override
	public void run() {
		ServerSocket serverSocket= serverSocketModel.getServerSocket();
		if(serverSocket==null){
			return;
		}
		try {
			while (true) {
					Socket clientSocket = serverSocket.accept();//取客户连接
					MyLog.info("监听到端口连接请求"+serverSocketModel.getPort()+"。发起请求端ip:"+clientSocket.getInetAddress());
					//创建socketmodel
					SocketModel socketModel = new SocketModel();
					socketModel.setServerSocketModel(serverSocketModel);
					socketModel.setSocket(clientSocket);
					if(Config.ServerSocketType.proxy.equals(serverSocketModel.getType())){
						socketModel.setConnId(IdGen.generateShortUuid());
						socketModel.setType(Config.SocketType.proxy);
						MyLog.info("创建proxy socket connId="+socketModel.getConnId());
						
					}
					SocketManager.getInstance().addSocket(socketModel);
					//输入输出流处理
					ReadStream readStream = new ReadStream(socketModel);
					WriteStream writeStream = new WriteStream(socketModel);
					socketModel.setReadStream(readStream);
					socketModel.setWriteStream(writeStream);
					readStream.start();
					writeStream.start();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}
